package com.weipt.juc.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author peter.wei 2020/09/10 09:25
 * @version 1.0
 * @company 终生学习
 * @description <br>peter.wei 2020/09/10 09:25 生产者消费者=>线程通讯问题
 * lock  await  signal 三剑客
 **/
public class HelloLockPC {

    public static void main(String[] args) {
        Data2 pc = new Data2();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    pc.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "A").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    pc.decrement();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "B").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    pc.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "C").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    pc.decrement();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "D").start();
    }
}

class Data2{
    private static int num = 0;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void increment() throws InterruptedException {
        lock.lock();
        try {
            //需要等待的条件
            while (num!=0){
                condition.await();
            }
            //执行逻辑
            num++;
            System.out.println(Thread.currentThread().getName()+"=>"+num);
            //逻辑执行完毕，通知别人
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            //需要等待的条件
            while (num==0){
                condition.await();
            }
            //执行逻辑
            num--;
            System.out.println(Thread.currentThread().getName()+"=>"+num);
            //通知别人
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}


